package com.bailiban.servlet;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.bailiban.pojo.Tickets;
import com.bailiban.service.TicketsService;
import com.bailiban.service.impl.TicketsServiceImpl;
import com.bailiban.utils.JedisPoolUtil;
import com.bailiban.utils.ResultMsg;
import com.fasterxml.jackson.databind.ObjectMapper;

import redis.clients.jedis.Jedis;

/**
 * Servlet implementation class TicketsServlet
 */
@WebServlet("/ticket")
public class TicketsServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private TicketsService ticketsService = new TicketsServiceImpl();
    private static Jedis jedis = null;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public TicketsServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String method = request.getParameter("method");
        ObjectMapper mapper = new ObjectMapper();
        response.setContentType("application/json;charset=utf-8");
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        Date beginTime = null;
        if ("findAll".equals(method)) {
            jedis = JedisPoolUtil.getJedis();
            // 先从redis中取门票tickets数据
            String tickets_json = jedis.get("tickets_json");
            // 判断redis中是否有tickets数据
            if (tickets_json == null || tickets_json.length() < 1) {
                // redis中没有数据，从数据库中取数据
                System.out.println("-------------redis中没有数据--------------");
                List<Tickets> list = ticketsService.findAllTickets();
                tickets_json = mapper.writeValueAsString(list);
                // 再把数据库中查询的数据存入redis缓存中
                System.out.println("-------------将数据库查询所得数据存入redis中--------");
                jedis.set("tickets_json", tickets_json);
                jedis.close();
            } else {
                System.out.println("redis中有数据");
            }
            response.getWriter().write(tickets_json);
        } else if ("delete".equals(method)) {

            jedis = JedisPoolUtil.getJedis();
            jedis.del("tickets_json");
            jedis.close();
            System.out.println("数据有变动，删除redis缓存");
            String[] ids = request.getParameterValues("tids");
            // int tid = Integer.parseInt(tids);
            List<Integer> tids = new ArrayList<Integer>();
            for (String string : ids) {
                int id = Integer.parseInt(string);
                tids.add(id);
            }
            ResultMsg resultMsg = ticketsService.deleteTicketsByTids(tids);
            String json = mapper.writeValueAsString(resultMsg);
            response.getWriter().write(json);
        } else if ("add".equals(method)) {
            jedis = JedisPoolUtil.getJedis();
            jedis.del("tickets_json");
            jedis.close();
            System.out.println("数据有变动，删除redis缓存");
            String tname = request.getParameter("tname");
            String beginTimes = request.getParameter("beginTime");

            try {
                beginTime = format.parse(beginTimes);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String totalCounts = request.getParameter("totalCount");
            int totalCount = Integer.parseInt(totalCounts);
            String orderCounts = request.getParameter("orderCount");
            int orderCount = Integer.parseInt(orderCounts);
            String prices = request.getParameter("price");
            double price = Double.parseDouble(prices);
            String description = request.getParameter("description");
            String s_t_ids = request.getParameter("s_t_id");
            int s_t_id = Integer.parseInt(s_t_ids);
            Tickets tickets = new Tickets();
            tickets.setBeginTime(beginTime);
            tickets.setDescription(description);
            tickets.setOrderCount(orderCount);
            tickets.setPrice(price);
            tickets.setS_t_id(s_t_id);
            tickets.setTname(tname);
            tickets.setTotalCount(totalCount);
            ResultMsg resultMsg = ticketsService.addTickets(tickets);
            String json = mapper.writeValueAsString(resultMsg);
            response.getWriter().write(json);

        } else if ("update".equals(method)) {
            jedis = JedisPoolUtil.getJedis();
            jedis.del("tickets_json");
            jedis.close();
            System.out.println("数据有变动，删除redis缓存");
            String tname = request.getParameter("tname");
            String beginTimes = request.getParameter("beginTime");
            String tids = request.getParameter("tid");
            int tid = Integer.parseInt(tids);
            try {
                beginTime = format.parse(beginTimes);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            String totalCounts = request.getParameter("totalCount");
            int totalCount = Integer.parseInt(totalCounts);
            String orderCounts = request.getParameter("orderCount");
            int orderCount = Integer.parseInt(orderCounts);
            String prices = request.getParameter("price");
            double price = Double.parseDouble(prices);
            String description = request.getParameter("description");
            String s_t_ids = request.getParameter("s_t_id");
            int s_t_id = Integer.parseInt(s_t_ids);
            Tickets tickets = new Tickets();
            tickets.setBeginTime(beginTime);
            tickets.setDescription(description);
            tickets.setOrderCount(orderCount);
            tickets.setPrice(price);
            tickets.setS_t_id(s_t_id);
            tickets.setTname(tname);
            tickets.setTotalCount(totalCount);
            tickets.setTid(tid);
            ResultMsg resultMsg = ticketsService.updateTickets(tickets);
            String json = mapper.writeValueAsString(resultMsg);
            response.getWriter().write(json);

        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}
